package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.*;
import com.bwie.poi.ExcelUtil;
import com.bwie.pojo.*;
import com.bwie.service.TbOrderRecordService;
import com.bwie.service.TbOrderService;
import com.bwie.utils.Result;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 39304
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2025-06-03 14:00:26
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{
    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    TbProdInfoMapper tbProdInfoMapper;

    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;

    @Autowired
    TbProdMapper tbProdMapper;

    @Autowired
    TbProdImageMapper tbProdImageMapper;

    @Autowired
    HttpServletResponse response;

    @Autowired
    TbOrderRecordMapper tbOrderRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addOrder(List<TbProdInfo> prodInfoList) {
        String token = request.getHeader("token");
        if (token == null){
            return Result.error().setMsg("请先登录");
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        String userName = body.get("userName", String.class);
        String realName = body.get("realName", String.class);

        BigDecimal amount = new BigDecimal(0.0);
        StringBuilder nameList = new StringBuilder();
        Integer total = 0;
        for (TbProdInfo tbProdInfo : prodInfoList) {
            TbProdInfo prodInfo = tbProdInfoMapper.selectById(tbProdInfo.getInfoId());
            if (tbProdInfo.getBuyNum() > prodInfo.getProdStock()){
//                return Result.error().setMsg("库存不足");
                throw new RuntimeException("库存不足");
            }else {
                prodInfo.setProdStock(prodInfo.getProdStock() - tbProdInfo.getBuyNum());
                tbProdInfoMapper.updateById(prodInfo);
            }

            amount = prodInfo.getProdPrice().multiply(new BigDecimal(tbProdInfo.getBuyNum())).add(amount);

            TbProd tbProd = tbProdMapper.selectById(prodInfo.getProdId());
            if (nameList.length() == 0){
                nameList.append(tbProd.getProdName()).append(prodInfo.getAttrColor());
            }else {
                nameList.append(",").append(tbProd.getProdName()).append(prodInfo.getAttrColor());
            }

            //计算商品数量
            total = tbProdInfo.getBuyNum();
        }

        TbOrder tbOrder = new TbOrder();
        tbOrder.setUserId(userId);
        tbOrder.setCreateBy(realName);
        tbOrder.setCreateTime(new Date());

        //雪花算法生成订单ID
        long orderNo = IdUtil.getSnowflake(1, 1).nextId();
        System.out.println("订单ID" + orderNo);

        tbOrder.setOrderNo(orderNo);
        tbOrder.setOrderStatus(0);
        tbOrder.setAmount(amount);
        tbOrder.setOrderType(0);
        tbOrder.setCoupon(0);
        tbOrder.setDellvery("");

        //设置购买商品的名称列表
        tbOrder.setProdInfo(nameList.toString());

        //购买商品的数量
        tbOrder.setProdNum(total);

        tbOrder.setUseScore(0);

        //保存订单
        tbOrderMapper.insert(tbOrder);

        for (TbProdInfo tbProdInfo : prodInfoList) {
            TbOrderDetail tbOrderDetail = new TbOrderDetail();
            tbOrderDetail.setOrderId(tbOrder.getOrderId());
            tbOrderDetail.setProdId(tbProdInfo.getProdId());
            tbOrderDetail.setProdNum(tbProdInfo.getBuyNum());
            tbOrderDetail.setProdPrice(tbProdInfo.getProdPrice());

            tbOrderDetailMapper.insert(tbOrderDetail);
        }

        //新增订单记录
        TbOrderRecord tbOrderRecord = new TbOrderRecord();
        //与订单ID关联
        tbOrderRecord.setOrderId(tbOrder.getOrderId());
        //与商品ID关联
        Integer prodId = prodInfoList.get(0).getProdId();
        tbOrderRecord.setProdId(prodId);
        tbOrderRecord.setRecordContent("用户订单创建");
        tbOrderRecord.setCreateTime(new Date());

        tbOrderRecordMapper.insert(tbOrderRecord);


        return Result.ok();
    }

    @Override
    public Result getOrderList(PageInfoVo pageInfoVo) {
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

//        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
//        wrapper.lambda().orderByDesc(TbOrder::getCreateTime);
//
//        Page<TbOrder> tbOrderPage = tbOrderMapper.selectPage(page, wrapper);

        Page<TbOrder> tbOrderPage = tbOrderMapper.getOrderList(page,pageInfoVo);

        tbOrderPage.getRecords().forEach(tbOrder -> {
            List<TbOrderDetail> tbOrderDetails = tbOrderDetailMapper.selectList(
                    new QueryWrapper<TbOrderDetail>().lambda().eq(TbOrderDetail::getOrderId, tbOrder.getOrderId())
            );

            tbOrderDetails.forEach(tbOrderDetail -> {
                List<TbProdImage> tbProdImages = tbProdImageMapper.selectList(
                        new QueryWrapper<TbProdImage>().lambda().eq(TbProdImage::getProdId, tbOrderDetail.getProdId())
                );

                //使用stream流转为图片 列表
                List<String> imageList = tbProdImages.stream().map(item -> item.getImageUrl()).collect(Collectors.toList());

                //设置 图片列表
                tbOrderDetail.setImageList(imageList);

                tbOrder.setImageList(imageList);
            });

            //把订单详情列表 设置到 订单对象中
            tbOrder.setOrderDetailList(tbOrderDetails);


        });

        return Result.ok().setData(tbOrderPage);
    }

    @Override
    public Result deleteAll(List<TbOrder> tbOrderList) {
        for (TbOrder tbOrder : tbOrderList) {
            TbOrder order = tbOrderMapper.selectById(tbOrder.getOrderId());
            if (order == null){
                throw new RuntimeException("订单不存在");
            }
            tbOrderDetailMapper.delete(
                    new QueryWrapper<TbOrderDetail>().lambda().eq(TbOrderDetail::getOrderId,tbOrder.getOrderId())
            );

            tbOrderMapper.deleteById(tbOrder.getOrderId());
        }

        return Result.ok();
    }

    @Override
    public void exportExcel(String ids) {
        //ids = 1,2,5
        String[] idList = ids.split(",");
        ArrayList<Integer> integers = new ArrayList<>();
        for (String id : idList) {
            integers.add(Integer.parseInt(id));
        }

        //查询订单列表
        List<TbOrder> tbOrders = tbOrderMapper.selectBatchIds(integers);

        //导出文件
        ExcelUtil<TbOrder> excelUtil = new ExcelUtil<TbOrder>(TbOrder.class);
        excelUtil.exportExcel(response,tbOrders,"订单列表");


    }
}




